<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="grander">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tbody v-if="list.length">
          <tr v-for="(item, index) in list" :key="item.id">
            <td>{{ index + 1 }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.grander }}</td>
            <td>
              <button @click="del(item.id)">删除</button>
              <button @click="edit(index)">编辑</button>
            </td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="5">
              <span>暂无数据</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list")) || [],
      // list: [
      //   { id: "1", name: "zs", age: 19, grander: "男" },
      //   { id: "2", name: "ls", age: 19, grander: "男" },
      //   { id: "3", name: "ww", age: 19, grander: "男" },
      //   { id: "4", name: "wmz", age: 19, grander: "男" },
      // ],
      name: "",
      age: "",
      grander: "",
      id: "",
    };
  },
  methods: {
    add() {
      if (this.name === "" || this.age === "" || this.grander === "")
        return alert("请填写完整");
      if (this.id === "") {
        const obj = {
          id: +new Date(),
          name: this.name,
          age: this.age,
          grander: this.grander,
        };
        this.list.push(obj);
      } else {
        const index = this.list.findIndex((item) => item.id === this.id);
        this.list[index].name = this.name;
        this.list[index].age = this.age;
        this.list[index].grander = this.grander;
      }
      this.name = "";
      this.age = "";
      this.grander = "";
      this.id = "";
    },
    del(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    edit(id) {
      this.name = this.list[id].name;
      this.age = this.list[id].age;
      this.grander = this.list[id].grander;
      this.id = this.list[id].id;
    },
  },
  watch: {
    list: {
      deep: true,
      immediate: true,
      handler(newValue) {
        localStorage.setItem("list", JSON.stringify(newValue));
      },
    },
  },
};
</script>
